from flask import render_template, request, jsonify, g, current_app, abort
from werkzeug.utils import redirect

from info import constants, db
from info.models import Category, News, User
from info.modules.profile import profile_blu
from info.utils.commom import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET


@profile_blu.route("/other_news_list")
def other_news_list():
    """返回指定用户的发布的新闻"""
    # 取到参数，你要看你关注的哪个人的id,和当前页数
    other_id = request.args.get("user_id")
    page = request.args.get("p",1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    if not other:
        return jsonify(errno=RET.NODATA, errmsg="当前用户不存在")
    try:
        paginate = other.news_list.paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    news_dict_li = []
    for news_item in news_li:
        news_dict_li.append(news_item.to_basic_dict())

    data = {
         "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@profile_blu.route("/other_info")
@user_login_data
def other_info():
    #  点击关注的人，显示他的界面的信息。
    user = g.user

    other_id = request.args.get("user_id")

    if not other_id:
        abort(404)
    # 查询指定id的用户信息
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other:
        abort(404)

    # 在点击进去别人的主页的时候显示看是否已经关注过
    is_followed = False
    if user and other:
        if other in user.followed:
            is_followed = True

    data = {
        "user":g.user.to_dict() if g.user else None,
        "is_followed":is_followed,
        "other_info":other.to_dict()
    }
    return render_template("news/other.html",data = data)


@profile_blu.route("/user_follow")
@user_login_data
def user_follow():
    # 获取页数
    p = request.args.get("p",1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 取到当前登录的用户
    user = g.user

    follows = []
    current_page =1
    total_page = 1
    try:
        paginate = user.followed.paginate(p,constants.USER_FOLLOWED_MAX_COUNT,False)
        #获取当前页的数据
        follows = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())
    data = {
        "user":user_dict_li,
        "total_page":total_page,
        "current_page":current_page
    }

    return render_template("news/user_follow.html",data = data)
@profile_blu.route("/news_list")
@user_login_data
def user_news_list():
    #获取参数
    page = request.args.get("p",1)

    #t判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    user = g.user
    news_list = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_review_dict())

    data = {
        "news_list":news_dict_li,
        "total_page":total_page,
        "current_page":current_page
    }

    return render_template("news/user_news_list.html",data = data)


#修改个人资料，头像，密码 ，新闻发布都是get,post两种请求
#只有收藏不是
@profile_blu.route("/news_release")
def news_release():
    if request.method=="GET":
        #加载新闻分类数据
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        category_dict_li = []
        for category in categories:
            category_dict_li.append(category.to_dict())

        # 移除最新的分类
        category_dict_li.pop(0)
        return render_template("news/user_news_release.html",data = {"categories":category_dict_li})

    # 如果要发布新闻
    # 获取参数
    #标题
    title = request.form.get("title")
    #新闻来源
    source = "个人发布"
    #摘要
    digest = request.form.get("digest")
    #新闻内容
    content = request.form.get("content")
    #索引图片
    index_image = request.files.get("index_image")
    # 分类id
    category_id = request.form.get("category_id")

    # 校验参数
    # 2.1 判断数据是否有值
    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")


    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    #取到图片，将图片上传到七牛云
    try:
        index_image_data = index_image.read()
        key = storage(index_image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    # 1代表审核状态
    news.status = 1

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
    return jsonify(errno=RET.OK, errmsg="OK")


@profile_blu.route("/collection")
@user_login_data
def user_collection():
    # 获取页数
    page = request.args.get("p",1)

    #检验，判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    user = g.user
    news_list = []
    total_page = 1
    current_page = 1
    try:
        paginate = user.collection_news.paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        current_page = paginate.page
        total_page = paginate.pages
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "collections": news_dict_li
    }

    return render_template("news/user_collection.html",data=data)


# 如果式get请求就直接渲染模板然后返回，如果式post,
#先获取旧的密码和新的密码，判断是否为空
#再去用user里边的check_password去查看旧密码是否正确
#如果正确，去user.password = news_password
# 修改密码的前后端实现
@profile_blu.route("/pass_info",methods=["GET","POST"])
@user_login_data
def pass_info():
    if request.method=="GET":
        return render_template("news/user_pass_info.html")

    # 获取参数
    old_password = request.json.get("old_password")
    news_password = request.json.get("new_password")

    # 2. 校验参数
    if not all([old_password, news_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 判断旧密码是否正确，用到user里边的check_password这个方法
    user = g.user
    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原密码错误")
    #设置新密码
    user.password = news_password
    return jsonify(errno=RET.OK, errmsg="保存成功")


#先从files中取出图片。read()
# 利用七牛云上传图片利用包装的那个storage(f.read)来获取key,图片的保存地址
#user = g.user, user里边de avatar_url属性用户头像的路径来保存，然后返回
@profile_blu.route("/pic_info",methonds = ["GET","POST"])
@user_login_data
def pic_info():
    user = g.user
    if request.method =="GET":
        return render_template("news/user_pic_info.html",data = {"user":g.user.to_dict()})

    try:
        avatar = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    try:
        key = storage(avatar)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传头像失败")
    # 保存头像地址
    user.avatar_url = key
    return jsonify(errno=RET.OK, errmsg="OK", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + key})


# 修改用户信息， 取到参数，新的名字，新的性别，判断是不是在women和men中
#在user = g.user, user.nick_name = nickname
@profile_blu.route("/base_info",methods=["GET,POST"])
@user_login_data
def base_info():
    # 不同的请求方式，做不同的事情
    if request.method =="GET":
        return render_template("news/user_base_info.html",data = {"user":g.user.to_dict()})

    # 如果不是get,那么就是post请求
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")
    #校验参数
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if gender not in ("WOMAN", "MAN"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    user = g.user
    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender

    return jsonify(errno =RET.OK,errmsg = "OK")




@profile_blu.route("/info")
@user_login_data
def user_info():
    user = g.user
    if not user:
        return redirect("/")
    data = {
        "user":user.to_dict()
    }
    return render_template("news/user.html",data=data)